package com.giggle.mybatis.condition;

import com.giggle.common.helper.ReflectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Iterator;
import java.util.Map;

/**
 * @author guozichen
 * @ClassName:
 * @Description: (这里用一句话描述累的作用)
 * @date 2020/8/31 10:58
 */
public class InitDataSourceCondition implements Condition {

    private static final Logger logger = LoggerFactory.getLogger(InitDataSourceCondition.class);
    private static final String BEAN_DATASOURCE = "dataSource";
    private static final String BEAN_DEFINITION_MAP = "beanDefinitionMap";

    public InitDataSourceCondition() {
    }

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        try {
            Boolean isContain = conditionContext.getBeanFactory().containsBean(BEAN_DATASOURCE);
            if (isContain) {
                Map<String, BeanDefinition> beanDefinitionMap = (Map)ReflectHelper.getFieldValue(conditionContext.getBeanFactory(), BEAN_DEFINITION_MAP);
                Map.Entry<String, BeanDefinition> datasource = null;
                Iterator var6 = beanDefinitionMap.entrySet().iterator();

                while(var6.hasNext()) {
                    Map.Entry<String, BeanDefinition> entry = (Map.Entry)var6.next();
                    if (BEAN_DATASOURCE.equals(entry.getKey())) {
                        datasource = entry;
                        break;
                    }
                }

                if (datasource != null) {
                    beanDefinitionMap.remove(datasource.getKey(), datasource.getValue());
                    ReflectHelper.setFieldValue(conditionContext.getBeanFactory(), BEAN_DEFINITION_MAP, beanDefinitionMap);
                }
            }
        } catch (Exception var8) {
            logger.error("替换datasource异常:{}", var8.getMessage());
        }

        return true;
    }
}
